﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using Newtonsoft.Json;
using System.Data;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 评议细则定义
    /// </summary>
    /// 
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class PeerReviewRuleController : AdminBaseController
    {
        /// <summary>
        /// 评议ID的逻辑类
        /// </summary>
        private BLL.PeerReviewIP peerReviewIPBll = new BLL.PeerReviewIP();

        //
        // GET: /Admin/PeerReviewRule/
        /// <summary>
        /// 评议细则定义主页
        /// </summary>
        /// <returns>视图</returns>
        /// 
        [AuthorityActionFilter("m_PeerReviewRule", Order = 1)]
        [LogPageActionFilter("评议细则定义", Order = 2)]
        public ActionResult Index()
        {
            BLL.PeerReview peerReviewBll = new BLL.PeerReview();

            DataSet ds = peerReviewBll.GetIsFtatus();

            string isFstatus = "";
            if (ds.Tables[0].Rows.Count > 0)
            {
                isFstatus = ds.Tables[0].Rows[0]["FStatus"].ToString();
            }
            else
            {
                isFstatus = "";
            }
            ViewData["isFstatus"] = isFstatus;

            

            return View();
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        /// <param name="beenVoterClsCd">类别编号</param>
        /// <param name="peerReviewID">主题ID</param>
        /// <returns>字符串判断</returns>
        public string Exists(string peerReviewRuleCd)
        {
            string str = "";
            BLL.PeerReviewRule peerReviewRuleBll = new BLL.PeerReviewRule();
            if (peerReviewRuleBll.Exists(peerReviewRuleCd))
            {
                str = "exists";
            }
            else
            {
                str = "noexists";
            }

            return str;

        }
        /// <summary>
        /// 是否存在选项
        /// </summary>
        /// <param name="peerReviewRuleScoreCd">选项编号</param>
        /// <returns>字符串判断</returns>
        public string ExistsOption(string peerReviewRuleScoreCd)
        {
            string str = "";
            BLL.PeerReviewRuleOption peerReviewRuleOptionBll = new BLL.PeerReviewRuleOption();
            if (peerReviewRuleOptionBll.Exists(peerReviewRuleScoreCd))
            {
                str = "exists";
            }
            else
            {
                str = "noexists";
            }

            return str;

        }
        /// <summary>
        /// 细则页面
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult PeerReviewRuleContent() 
        {
            Model.PeerReview peerReviewModel = new Model.PeerReview();
            BLL.PeerReview peerReviewBll = new BLL.PeerReview();
            List<Model.PeerReview> peerReviewList = peerReviewBll.GetList();

            BLL.PeerReviewResult peerReviewResultBll = new BLL.PeerReviewResult();
            DataSet ds = peerReviewResultBll.GetAllList();
            string visible = "false";
            if (ds.Tables[0].Rows.Count > 0) {
                visible = "true";
            }
            ViewData["visible"] = visible;

            bool isNull = false;
            if (peerReviewList.Count > 0)
            {
                isNull = true;
            }

            if (!isNull)//增加 
            {
                peerReviewList = new List<Model.PeerReview>();
                ViewData["type"] = "ADD";
                peerReviewModel.FIsLookIPControl = "Y";
                peerReviewModel.FIsVoteIPControl = "Y";
                peerReviewModel.FIsSelectAll = "Y";
                ViewData["table"] = GetPeerReviewRuleTable();
                ViewData["peerReviewID"] = "0";
            }
            else//修改
            {
                //给MODEL赋值
                foreach (Model.PeerReview model in peerReviewList) 
                {
                    peerReviewModel.FBeginDate = model.FBeginDate;
                    peerReviewModel.FEndDate = model.FEndDate;
                    peerReviewModel.FPeerReviewID = model.FPeerReviewID;
                    peerReviewModel.FTitle = model.FTitle;
                    peerReviewModel.FIsLookIPControl = model.FIsLookIPControl;
                    peerReviewModel.FIsVoteIPControl = model.FIsVoteIPControl;
                    peerReviewModel.FIsSelectAll = model.FIsSelectAll;
                    ViewData["peerReviewID"] = model.FPeerReviewID;
                }

                
                //加载IP

                BLL.PeerReviewIP peerReviewIPBll = new BLL.PeerReviewIP();
                List<Model.PeerReviewIP> peerReviewIPList = peerReviewIPBll.GetListPeerReviewIP(peerReviewModel.FPeerReviewID);

                var fIsVoteIPControlList = from c in peerReviewIPList where c.FProp == "1" select c;
                if (fIsVoteIPControlList.Count() > 0)
                {
                    BLL.IPGroup groupBll = new BLL.IPGroup();
                    List<Model.IPGroup> groupList1 = new List<Model.IPGroup>();
                    foreach (Model.PeerReviewIP model in fIsVoteIPControlList)
                    {
                        Model.IPGroup groupModel = groupBll.GetModel(model.FIPGroupID);
                        groupModel.StrFStartIP = GenerateUtil.LongToIP(groupModel.FStartIP);
                        groupModel.StrFEndIP = GenerateUtil.LongToIP(groupModel.FEndIP);
                        groupList1.Add(groupModel);
                    }
                    ViewData["votegroupIPs"] = JsonConvert.SerializeObject(groupList1);
                }


                fIsVoteIPControlList = from c in peerReviewIPList where c.FProp == "2" select c;
                if (fIsVoteIPControlList.Count() > 0)
                {

                    BLL.IPGroup groupBll = new BLL.IPGroup();
                    List<Model.IPGroup> groupList2 = new List<Model.IPGroup>();
                    foreach (Model.PeerReviewIP model in fIsVoteIPControlList)
                    {
                        Model.IPGroup groupModel = groupBll.GetModel(model.FIPGroupID);
                        groupModel.StrFStartIP = GenerateUtil.LongToIP(groupModel.FStartIP);
                        groupModel.StrFEndIP = GenerateUtil.LongToIP(groupModel.FEndIP);
                        groupList2.Add(groupModel);

                    }
                    ViewData["lookgroupIPs"] = JsonConvert.SerializeObject(groupList2);
                }

                //选项
                BLL.PeerReviewRuleOption peerReviewRuleOptionBll = new BLL.PeerReviewRuleOption();
                List<Model.PeerReviewRuleOption> peerReviewRuleOptionList = peerReviewRuleOptionBll.GetModelList("");
                if (peerReviewRuleOptionList.Count > 0)
                {
                    ViewData["returnValue"] = JsonConvert.SerializeObject(peerReviewRuleOptionList);
                }

                ViewData["table"] = GetPeerReviewRuleTable();
                ViewData["RuleSorce"] = GetScoreStr();

                ViewData["type"] = "EDIT";
            }


            return View(peerReviewModel);
        }


        /// <summary>
        /// 选项页面
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult ChooseRuleOption(string json) 
        {
            if (json == "")
            {
                ViewData["json"] = json; 
            }
            else {
                ViewData["json"] = json; 
            }

            return View();
        }

        /// <summary>
        /// 明细选项页面
        /// </summary>
        /// <param name="returnValue">细则明细</param>
        /// <param name="hdRuleSorce">得分</param>
        /// <returns>视图</returns>
        public ActionResult Choose(string returnValue, string hdRuleSorce)
        {

            ViewData["returnValue"] = returnValue;
            ViewData["hdRuleSorce"] = hdRuleSorce;

            return View();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="peerReviewModel">peerReviewModel对象</param>
        /// <returns>视图</returns>
        public ActionResult Save(Model.PeerReview peerReviewModel)
        {
            string type = Fetch.Post("hdtype");

            peerReviewModel = GetPeerReviewModel(type);
            List<Model.PeerReviewIP> peerReviewIPList = GetPeerReviewIPList();
            List<Model.PeerReviewRuleOption> peerReviewRuleOptionList = GetPeerReviewRuleOptionList();
            List<Model.PeerReviewRule> peerReviewRuleList = GetPeerReviewRuleList();

            BLL.PeerReview peerReviewBll = new BLL.PeerReview();

            
            ViewData["type"] = type;
            if (type == "ADD")
            {
                try
                {
                    peerReviewBll.Add(peerReviewModel, peerReviewIPList, peerReviewRuleOptionList, peerReviewRuleList);

                    ViewData["message"] = "增加操作成功";
                }
                catch (Exception) 
                {
                    ViewData["message"] = "增加操作失败";
                }
            }
            else if (type == "EDIT")
            {
                if (peerReviewRuleList != null)
                {
                    try
                    {
                        peerReviewBll.Update(peerReviewModel, peerReviewIPList, peerReviewRuleOptionList, peerReviewRuleList);
                        ViewData["message"] = "修改操作成功";
                    }
                    catch
                    {
                        ViewData["message"] = "修改操作失败";
                    }
                }
                else 
                {
                    try
                    {
                        peerReviewBll.UpdateTwoList(peerReviewModel, peerReviewIPList, peerReviewRuleOptionList);
                        ViewData["message"] = "修改操作成功";
                    }
                    catch
                    {
                        ViewData["message"] = "修改操作失败";
                    }
                }
            }

            ViewData["join"] = true;
            ViewData["con"] = true;
            ViewData["table"] = GetPeerReviewRuleTable();
            ViewData["peerReviewID"] = peerReviewModel.FPeerReviewID;
            

            return View("PeerReviewRuleContent", peerReviewModel);
        }


        /// <summary>
        /// 得到主题类
        /// </summary>
        /// <returns></returns>
        /// <param name="type">修改还是增加</param>
        /// <returns>PeerReviewModel对象</returns>
        private Model.PeerReview GetPeerReviewModel(string type)
        {

            Model.PeerReview peerReviewModel = new Model.PeerReview();

            peerReviewModel.FTitle = Fetch.Post("FTitle").Trim();
            if (Fetch.Post("FBeginDate").Trim() != string.Empty)
            {
                peerReviewModel.FBeginDate = DateTime.Parse(Fetch.Post("FBeginDate"));
            }
            if (Fetch.Post("FEndDate").Trim() != string.Empty)
            {
                peerReviewModel.FEndDate = DateTime.Parse(Fetch.Post("FEndDate")).AddDays(1).AddSeconds(-1);
            }
            if (type == "ADD")
            {
                peerReviewModel.FPeerReviewID = peerReviewModel.FPeerReviewID;
            }
            else 
            {
                peerReviewModel.FPeerReviewID = decimal.Parse(Fetch.Post("hdPeerReviewID"));
            }
            peerReviewModel.FStatus = "N";
            peerReviewModel.FIsSelectAll = CheckBoxExtension.GetValue<bool>("FIsSelectAll") == true ? "Y" : "N";
            peerReviewModel.FIsVoteIPControl = CheckBoxExtension.GetValue<bool>("joinISIP") == true ? "Y" : "N";
            peerReviewModel.FIsLookIPControl = CheckBoxExtension.GetValue<bool>("conISIP") == true ? "Y" : "N";

            return peerReviewModel;
        }

        /// <summary>
        /// 得到IP集合
        /// </summary>
        /// <returns>IP集合</returns>
        private List<Model.PeerReviewIP> GetPeerReviewIPList() {
            List<Model.PeerReviewIP> peerReviewIPList = new List<Model.PeerReviewIP>();
            Model.PeerReviewIP peerReviewIP;

            bool fIsVoteIPControl = CheckBoxExtension.GetValue<bool>("joinISIP");
            if (fIsVoteIPControl)
            {
                string[] arrayids = Fetch.Post("hdjoinID").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < arrayids.Length; i++)
                {
                    peerReviewIP = new Model.PeerReviewIP();
                    peerReviewIP.FIPGroupID = Int32.Parse(arrayids[i]);
                    ViewData["joinGroupID"] += arrayids[i];
                    peerReviewIP.FProp = "1";
                    peerReviewIP.FPeerReviewID = decimal.Parse(Fetch.Post("hdPeerReviewID"));
                    peerReviewIPList.Add(peerReviewIP);
                }

            }

            bool fIsLookIPControl = CheckBoxExtension.GetValue<bool>("conISIP");
            if (fIsLookIPControl)
            {
                string[] arrayids = Fetch.Post("hdconID").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < arrayids.Length; i++)
                {
                    peerReviewIP = new Model.PeerReviewIP();
                    peerReviewIP.FIPGroupID = Int32.Parse(arrayids[i]);
                    ViewData["conGroupID"] += arrayids[i];
                    peerReviewIP.FProp = "2";
                    peerReviewIP.FPeerReviewID = decimal.Parse(Fetch.Post("hdPeerReviewID"));
                    peerReviewIPList.Add(peerReviewIP);
                }

            }

            return peerReviewIPList;
        }

        /// <summary>
        /// 得到评议选项
        /// </summary>
        /// <returns>评议选项集合</returns>
        private List<Model.PeerReviewRuleOption> GetPeerReviewRuleOptionList()
        {
            string strJson = Fetch.Post("hdreturnValue").Trim();
            List<Model.PeerReviewRuleOption> peerReviewRuleOptionList = JsonConvert.DeserializeObject<List<Model.PeerReviewRuleOption>>(strJson);

            return peerReviewRuleOptionList;
        }

        /// <summary>
        /// 评议细则
        /// </summary>
        /// <returns>细则集合</returns>
        private List<Model.PeerReviewRule> GetPeerReviewRuleList() 
        {
            string strJson = Fetch.Post("hdresult").Trim();

            List<Model.PeerReviewRule> peerReviewRuleList = new List<Model.PeerReviewRule>();
            peerReviewRuleList = JsonConvert.DeserializeObject<List<Model.PeerReviewRule>>(strJson);
            
            return peerReviewRuleList;
        }

        /// <summary>
        /// 得到细则的table
        /// </summary>
        /// <returns>字符串</returns>
        private string GetPeerReviewRuleTable() 
        {
            string str = "";
            BLL.PeerReviewRule peerReviewRuleBll = new BLL.PeerReviewRule();
            BLL.PeerReviewRuleScore peerReviewRuleScoreBll = new BLL.PeerReviewRuleScore();
            BLL.PeerReviewRuleOption peerReviewRuleOptionBll = new BLL.PeerReviewRuleOption();
            List<Model.PeerReviewRule> peerReviewRuleList = peerReviewRuleBll.GetModelList("");
            int i = 0;
            string tableName = "additem";
            if (peerReviewRuleList.Count > 0)
            {
                peerReviewRuleList = peerReviewRuleList.OrderBy(c => c.FDispSeq).ToList();
                foreach (Model.PeerReviewRule peerReviewRulemodel in peerReviewRuleList)
                {
                    string josn = "";
                    i++;
                    str += "<tr class=\"Add\" id=\"" + i + "\"><td align='center' class='tdClass'><img src=\"" + Url.Content("~/Content/images/delete.gif") + "\" width='9' height='9' style='cursor:pointer' onclick=delRow('" + tableName + "','" + i + "') />";
                    str += "<td align=\"center\" class=\"tdClass\"><input type=\"text\" style=\"width:60px\" value=\"" + peerReviewRulemodel.FPeerReviewRuleCd + "\" /></td>";
                    str += "<td align=\"center\" class=\"tdClass\"><input type=\"text\" style=\"width:60px\" value=\"" + peerReviewRulemodel.FRuleCls + "\"  /></td>";
                    str += "<td align=\"center\" class=\"tdClass\"><input type=\"text\" style=\"width:600px\" value=\"" + peerReviewRulemodel.FRuleNote + "\"  /></td>";
                    str += "<td align=\"center\" class=\"tdClass\"><input type=\"text\" style=\"width:50px\" onkeyup=\"this.value=this.value.replace(/[^\\d]/g,'')\" onafterpaste=\"this.value=this.value.replace(/[^\\d]/g,'')\" value=\"" + peerReviewRulemodel.FScore + "\"  /></td>";
                    str += "<td align=\"center\" class=\"tdClass\"><input type=\"text\" style=\"width:50px\" onkeyup=\"this.value=this.value.replace(/[^\\d]/g,'')\" onafterpaste=\"this.value=this.value.replace(/[^\\d]/g,'')\" value=\"" + peerReviewRulemodel.FDispSeq + "\"  /></td>";
                    str += "<td align='center' class='tdClass' style=\"font-size: 12px;\"><a href=\"#\" onclick=\"choose(this)\">[编辑]</a></td>";
                    str += "<td class=\"tdClass\" align=\"center\" style=\"font-size: 12px;\">";
                    List<Model.PeerReviewRuleScore> peerReviewRuleScoreList = peerReviewRuleScoreBll.GetModelList(" a.FPeerReviewRuleScoreCd =b.FPeerReviewRuleScoreCd ");

                    peerReviewRuleScoreList = peerReviewRuleScoreList.Where(s => s.FPeerReviewRuleCd == peerReviewRulemodel.FPeerReviewRuleCd).ToList();
                    foreach (Model.PeerReviewRuleScore peerReviewRuleSocreModel in peerReviewRuleScoreList)
                    {
                        //if (peerReviewRulemodel.FPeerReviewRuleCd == peerReviewRuleSocreModel.FPeerReviewRuleCd)
                        //{
                            string scoreName = peerReviewRuleOptionBll.GetScoreNameByScoreCd(peerReviewRuleSocreModel.FPeerReviewRuleScoreCd);

                            str += scoreName + ":" + peerReviewRuleSocreModel.FScore + "<br />";
                            josn = JsonConvert.SerializeObject(peerReviewRuleScoreList);
                            str += "<input type='hidden' value='" + josn + "'/>";
                        //}
                    }
                    str += "</td></tr>";
                }
            }

            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetScoreStr() {

            string scoreStr = "";
            BLL.PeerReviewRule peerReviewRuleBll = new BLL.PeerReviewRule();
            BLL.PeerReviewRuleScore peerReviewRuleScoreBll = new BLL.PeerReviewRuleScore();
            BLL.PeerReviewRuleOption peerReviewRuleOptionBll = new BLL.PeerReviewRuleOption();
            List<Model.PeerReviewRule> peerReviewRuleList = peerReviewRuleBll.GetModelList("");
            List<Model.PeerReviewRuleScore> peerReviewRuleScoreList = new List<Model.PeerReviewRuleScore>();
            if (peerReviewRuleList.Count > 0)
            {
                scoreStr += "[";
                foreach (Model.PeerReviewRule peerReviewRulemodel in peerReviewRuleList)
                {
                    peerReviewRuleScoreList = peerReviewRuleScoreBll.GetModelList(" a.FPeerReviewRuleScoreCd =b.FPeerReviewRuleScoreCd ");
                    peerReviewRuleScoreList = peerReviewRuleScoreList.Where(s => s.FPeerReviewRuleCd == peerReviewRulemodel.FPeerReviewRuleCd).ToList();
                    foreach (Model.PeerReviewRuleScore peerReviewRuleSocreModel in peerReviewRuleScoreList)
                    {
                        string scoreName = peerReviewRuleOptionBll.GetScoreNameByScoreCd(peerReviewRuleSocreModel.FPeerReviewRuleScoreCd);
                        scoreStr += "{";
                        scoreStr += "\"FPeerReviewRuleCd\":\"" + peerReviewRuleSocreModel.FPeerReviewRuleCd + "\",\"FPeerReviewRuleScoreCd\":\"" + peerReviewRuleSocreModel.FPeerReviewRuleScoreCd + "\",\"FScoreName\":\"" + scoreName + "\",\"FScore\":" + peerReviewRuleSocreModel.FScore;
                        scoreStr += "},";
                    }                                      
                }
                if (peerReviewRuleScoreList.Count > 0)
                {
                    scoreStr = scoreStr.Substring(0, scoreStr.LastIndexOf(","));
                }
                scoreStr += "]";
                
            }
            return scoreStr;
        }


    }
}
